package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.JwtUtil;
import com.itheima.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/user")/*指定请求的映射路径*/
@Validated
public class UserController {
    // 手机号正则表达式（静态常量，复用正则对象提高效率）
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@jakarta.validation.constraints.Pattern(regexp = "^\\S{5,16}$") String username,
                           @jakarta.validation.constraints.Pattern(regexp = "^\\S{5,16}$")String password,
                           @jakarta.validation.constraints.Pattern(regexp = "^1[3-9]\\d{9}$") String userphone) {
        //查询用户
        User u = userService.findByUserName(username);
        if (u == null) {
            //没有占用
            userService.register(username, password, userphone);
            return Result.success("注册成功");
        } else {
            //占用
            return Result.error("用户名已被占用");
        }
    }
    @PostMapping("/login")
    public Result<String> login(@jakarta.validation.constraints.Pattern(regexp = "^\\S{5,16}$") String username,
                                @jakarta.validation.constraints.Pattern(regexp = "^\\S{5,16}$")String password){
        //根据用户名查询用户
        User loginUser = userService.findByUserName(username);
        //判断该用户是否存在
        if(loginUser==null){
            return Result.error("用户名错误");
        }
        //判断密码是否正确 loginUser对象中的password是否是密文
        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            //登录成功
            Map<String,Object> claims=new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }
}